<template>
  <div class="article">
    <Form
      :label-width="118"
      :model="formData"
      ref="formItem"
      :rules="infoRules"
      class="list"
    >
      <Row :gutter="32">
        <i-col span="16">
          <FormItem label="栏目" prop="list_id">
            <TreeSelect :max-tag-count="2" v-model="formData.list_id" :data="topicList"
                                                clearable ></TreeSelect>
            
          </FormItem>
          <FormItem label="标题" prop="title">
            <Input placeholder="请输入标题" v-model="formData.title" />
          </FormItem>
          <FormItem label="视频ID" prop="video_id">
          <Input
            placeholder="请输入视频ID,视频ID从视频后台获取"
            v-model="formData.video_id"
          />
      </FormItem>
      <FormItem label="视频封面" prop="cover_img" :rules="formData.video_id?[{ required: true, message: '请选择视频封面', trigger: 'bulr' }]:infoRules.cover_img">
        <div v-if="formData.cover_img" class="demo-upload-list">
          <img :src="formData.cover_img" width="100" height="100" />
          <div class="demo-upload-list-cover">
                <Icon type="ios-trash-outline" @click="formData.cover_img=''"></Icon>
            </div>
        </div>
        <div class="imageUpdate">
          <Upload
            ref="upload"
            name="file"
            :show-upload-list="false"
            :on-success="handleSuccess1"
            :format="['jpg', 'jpeg', 'png']"
            :action="requestAction"
            :before-upload="handleBefore1"
          >
            <div>
              <Button
                type="primary"
                class="ivu-mr-8"
                size="small"
                :loading="loading1"
              >
                {{ loading1 ? "上传中..." : "上传" }}
              </Button>
            </div>
          </Upload>
          <Button type="success" size="small" @click="showImgModel1 = true"
            >选择</Button
          >
        </div>
      </FormItem>
          <FormItem label="内容" prop="content">
            <ckeditor
              :editor="editor"
              v-model="formData.content"
              :config="editorConfig"
            ></ckeditor>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="缩略图" :label-width="80">
            <div v-if="formData.thumb" class="demo-upload-list">
              <img :src="formData.thumb" width="100" height="100" />

              <div class="demo-upload-list-cover">
                <Icon type="ios-trash-outline" @click="formData.thumb=''"></Icon>
            </div>
            </div>
            <div class="imageUpdate">
              <Upload
                ref="upload"
                name="file"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg', 'jpeg', 'png']"
                :action="requestAction"
                :before-upload="handleBefore"
              >
                <div>
                  <Button
                    type="primary"
                    class="ivu-mr-8"
                    size="small"
                    :loading="loading"
                    >{{ loading ? "上传中..." : "上传" }}</Button
                  >
                </div>
              </Upload>
              <Button type="success" size="small" @click="showImgModel = true"
                >选择</Button
              >
            </div>
          </FormItem>
          <FormItem label="发布人" prop="publisher_id" :label-width="80">
            <Select v-model="formData.publisher_id">
              <Option
                v-for="item in members"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="标签" :label-width="80">
            <Select
              v-model="model1"
              filterable
              multiple
              ref="tag"
              allow-create
              @on-change="selectTag"
              @on-create="handleCreate2"
              placeholder="输入后Enter确认"
            >
              <Option
                v-for="item in tagList"
                :value="item.value"
                :key="item.value"
                :disabled="item.disabled == 0 ? true : false"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="描述" :label-width="80">
            <Input type="textarea" v-model="formData.description" :rows="4" />
          </FormItem>
          <FormItem label="作者" :label-width="80">
            <Input placeholder="请输入文章作者" v-model="formData.author" />
          </FormItem>
          <FormItem label="排序" class="ivu-inline-block" :label-width="80">
            <InputNumber
              style="width: 100%"
              :min="0"
              :precision="0"
              v-model="formData.sort"
            />
          </FormItem>
          <FormItem label="浏览" class="ivu-inline-block" :label-width="80">
            <InputNumber style="width: 100%" :min="0" :precision="0" />
          </FormItem>
          <FormItem label="首页推荐" class="ivu-inline-block" :label-width="80">
            <Switch v-model="formData.show_home" />
          </FormItem>
          <FormItem label="状态" class="ivu-inline-block" :label-width="80">
            <Select
              v-model="formData.publish_type"
              style="width: 100%"
              @on-change="changeStatus"
            >
              <Option
                v-for="item in pubType"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem v-if="showTime" label="发布时间" :label-width="80">
            <DatePicker
              type="datetime"
              v-model="formData.publish_time"
              style="width: 100%"
              @on-change="timeChange"
            />
          </FormItem>
        </i-col>
      </Row>
    </Form>
    <glo-check v-model="showImgModel" @getImgArr="getImgArr" />
    <glo-check v-model="showImgModel1" @getImgArr="getImgArr1" />
  </div>
</template>
<script>
import { arcCondition, arcCreate } from "@/api/jzy.js"
import { updatefileTemp } from '@/api/set.js'
import ClassicEditor from "@ckeditor/ckeditor5-build-classic"
import CKEditor from "@ckeditor/ckeditor5-vue"
const ckUpload = require("../../../libs/ckeditorUplodImg5")
import Setting from '@/setting'
import util from '@/libs/util'
import { Message } from 'view-ui-plus'
export default {
  name: "modalName",
  components: { ckeditor: CKEditor.component },
  props: ['editorType', 'arcInfo','showModal'],
  data () {
    return {
      loading: false,
      loading1: false,
      showImgModel: false,
      showImgModel1: false,
      baseUrl: Setting.request.apiBaseURL,
      requestAction: '',
      editor: ClassicEditor,
      editorConfig: {
        language: "zh-cn",
        extraPlugins: [ckUpload.MyCustomUploadAdapterPlugin],
        fontSize: {
          options: [10, "default", 14, 16, 18, 24, 36, 48]
        },
        fullscreen: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            // this.modalstatus = true;
          },
        },
        material: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            this.modalstatus = true
            this.showlink = true
            this.img = ""
            this.isDobule = true
          },
        },
        mediaEmbed: {
            providers: [{
            name: 'myprovider',
            url: [
              /^lizzy.*\.com.*\/media\/(\w+)/,
              /^www\.lizzy.*/,
              /^.*/
            ],
            html: match => {
              //获取媒体url
              const input = match['input'];
            //console.log('input' + match['input']);
              return (
                '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 70%;">' +
                  `<iframe src="${input}" ` +
                    'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' +
                    'frameborder="0" allowtransparency="true" allow="encrypted-media">' +
                  '</iframe>' +
                '</div>'
              );
            }
          }]
        }
      },
      dateValue: "2022-09-08 06:05:00",
      formData: {
        title: "",
        list_id: "",
        thumb: "",
        tag: [],
        content: "",
        description: "",
        author: "",
        sort: 1,
        views: 0,
        publish_type: 1,
        publisher_id: JSON.parse(localStorage.getItem("userinfo"))["id"]+'',
        show_home: false,
        publish_time: "",
        file_id: "",
        cover_img:'',
        video_id:''
      },
      infoRules: {
        list_id: [{ required: true, message: "请选择栏目", trigger: "bulr" }],
        title: [{ required: true, message: "请输入标题", trigger: "bulr" }],
        content: [{ required: true, message: "请输入文章内容", trigger: "bulr" }],
        publisher_id: [{ required: true, message: "请选择发布人", trigger: "bulr" }],
        cover_img: [{ required: false, message: "请选择视频封面", trigger: "bulr" }]
      },
      topicList: [],
      members: [],
      pubType: [],
      tagList: [],
      initTagList: [],
      model1: [],
      showTime: false,
      defualtId:''
    }
  },
  methods: {
    handleBefore () {
      this.loading = true
    },
    handleSuccess (response, file, fileList) {
      this.formData.thumb = `${response.data.host}${response.data.image_url[0]}`
      this.formData.file_id = response.data.image_id[0]
      this.loading = false
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    handleBefore1 () {
      this.loading1 = true
    },
    handleSuccess1 (response, file, fileList) {
      this.formData.cover_img = `${response.data.host}${response.data.image_url[0]}`
      this.formData.file_id = response.data.image_id[0]
      this.loading1 = false
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    // 改变缩略图的函数
    getImgArr (arr) {
      this.formData.thumb = arr[0]
    },
    getImgArr1 (arr) {
      this.formData.cover_img = arr[0]
    },
    timeChange (e) {
      this.formData.publish_time = e
    },
    saveData () {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          this.formData.tag = []
          this.model1.forEach((item) => {
            let flag = true,add=true
            this.initTagList.forEach(ele => {
              if (+ele.value == +item) {
                this.formData.tag.push({ id: item, name: ele.label })
                flag = false
                add=false
              }
            })
            if (flag) {
              this.tagList.forEach(ele => {
                if (+ele.value == +item) {
                  this.formData.tag.push({ id: 0, name: ele.label })
                  flag = true
                   add=false
                }
              })
              if(add){
                this.formData.tag.push({ id: 0, name: item })
              }
              
            }
          })
          let params={...this.formData}
          params.show_home=params.show_home?1:0
          if (!this.editorType) {
            params.id = this.arcInfo.id
          }
          arcCreate(params).then(res => {
            this.getArcCondition()
            this.$emit('refresh', false)
          })
        }
      })
    },
    handleCreate2 (e) {
      if(e.trim().length<1){
        this.$Message['warning']('标签不能为空')
        return
      }else if (e.length > 6) {
        this.$Message['warning']('标签长度不能超过6')
        return
      } else {
        let add=true
        this.tagList.forEach(item=>{
          if(item.label==e){
            add=false
            return;
          }
        })
        if(add){
          var id=new Date().getTime()      
          this.tagList.push({
            value: id,
            label: e,
            disabled: '1',
          })  
        }
         
      }
    },
    selectTag (e) {
      this.tagList.forEach(item=>{
        if(e[e.length - 1]==item.label){            
         if(e.includes(+item.value)){
           e.pop()
         }else{
           e[e.length - 1]=+item.value
         }
        }
      })
      if (e.length && (e[e.length - 1].length > 6||e[e.length - 1].toString().trim().length<1)) {
        e.pop()
        return
      }
      if (e.length > 3) {
        this.$Message.warning("标签不能超过三个~")
        e.splice(3, 1)
        return
      }
    },
    changeStatus () {
      if (this.formData.publish_type == '0') {
        this.showTime = true
      } else {
        this.formData.publish_time = ''
        this.showTime = false
      }
    },
    transData(ls){
      return ls.map(obj=>{
          let result = {value:'',title:'',disabled:false,children:[]}
          if(obj.children && obj.children.length > 0){
              result.value = obj.id
              result.title = obj.name
              result.expand=true
              if(obj.type==2){
                result.disabled=true
              }
              result.children = this.transData(obj.children)
              return result
          } else {
              if(obj.type==2){
                result.disabled=true
              }
              result.value = obj.id
              result.title = obj.name
              result.expand=true
              return result
          }
      })
  },
    getArcCondition () {
      arcCondition().then((res) => {
        let arr=[]
        for(let i in res.lists){
          arr.push(res.lists[i])
        }
        this.topicList =this.transData(arr)
        this.members = res.member_list
        this.initTagList = [...res.tag_list]
        this.tagList = res.tag_list
        this.pubType = res.publish_type      
        this.defualtId=res.list_default_id
      })
    }
  },

  mounted () {
    this.requestAction = this.baseUrl + `/v1/upload/images?auth_access_token=${util.cookies.get('token')}&auth_project_id=${localStorage.getItem('currentProject')}`
    this.getArcCondition()
  },
  watch: {
    showModal () {
      this.$refs.formItem.resetFields()
      if (this.arcInfo.id) {
        this.formData = {
          title: this.arcInfo.title,
          list_id: this.arcInfo.list_id,
          thumb: this.arcInfo.thumb,
          content: this.arcInfo.content,
          description: this.arcInfo.description,
          author: this.arcInfo.author,
          sort: +this.arcInfo.sort,
          views: +this.arcInfo.a_views,
          publish_type: parseInt(this.arcInfo.is_publish),
          publisher_id: this.arcInfo.publisher_id,
          publish_time: this.arcInfo.publish_time,
          file_id: "",
          cover_img:this.arcInfo.cover_img,
          video_id:this.arcInfo.video_id,
          show_home: this.arcInfo.show_home == '1' ? true : false,
        }
        if(this.arcInfo.tag_id){
          this.model1 = this.arcInfo.tag_id.split(',')
        }else{
          this.model1=[]
        }
        
      } else {
        this.formData = {
          title: "",
          list_id: this.defualtId,
          thumb: "",
          tag: [],
          content: "",
          description: "",
          author: "",
          sort: 1,
          views: 0,
          publish_type: 1,
          publisher_id: JSON.parse(localStorage.getItem("userinfo"))["id"]+'',
          show_home: false,
          publish_time: "",
          file_id: "",
          cover_img:'',
          video_id:''
        }
        this.model1 = []
      }

      if (this.formData.publish_type == '0') {
        this.showTime = true
      } else {
        this.showTime = false
      }
    }
  }
};
</script>
<style lang='less'>
.imageUpdate {
  display: flex;
}
.imageUpdate button {
  vertical-align: top;
}
.ivu-form-item {
  margin-bottom: 20px;
}
.article .ivu-inline-block {
  width: 50%;
}
.list {
  padding-bottom: 20px;
}
.list .ck-editor__editable {
  height: 200px;
}
.demo-upload-list{
    display: inline-block;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
}
.demo-upload-list img{
    width: 100%;
    height: 100%;
}
.demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
}
.demo-upload-list:hover .demo-upload-list-cover{
    display: block;
}
.demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
}
.ivu-tree-arrow-disabled + .ivu-tree-title{
  color: #999;
  cursor: not-allowed;
}
</style>
